#!/bin/bash

# move_files.sh
# https://app.yinxiang.com/shard/s22/nl/4928451/ed3df83d-22db-48f2-a2a0-7b890188baca
# This script moves files from a source directory to a destination directory
# based on a specified file pattern. It handles filenames with spaces and 
# special characters correctly.
#
# Usage:
# ./move_files.sh <source_directory> <file_pattern> <destination_directory>
#
# Arguments:
# - source_directory: The directory where the files currently exist.
# - file_pattern: The pattern to match files (e.g., "*.txt" for all text files).
# - destination_directory: The directory where the files should be moved to.
#
# Example:
# ./move_files.sh ~/Downloads "*.pdf" ~/Documents/PDFs
#
# Note:
# The script checks for the existence of the source and destination directories
# and ensures that at least one file matches the pattern before attempting to move files.

move_files() {
    # Check if the correct number of arguments is provided
    if [ $# -ne 3 ]; then
        echo "Usage: move_files <source_directory> <file_pattern> <destination_directory>"
        return 1
    fi

    local src_dir=$1
    local file_pattern=$2
    local dest_dir=$3

    # Check if the source directory exists
    if [ ! -d "$src_dir" ]; then
        echo "Source directory '$src_dir' not found."
        return 1
    fi

    # Check if the destination directory exists
    if [ ! -d "$dest_dir" ]; then
        echo "Destination directory '$dest_dir' not found."
        return 1
    fi

    # Using find with -exec to handle filenames with spaces and special characters
    find "$src_dir" -maxdepth 1 -name "$file_pattern" -exec sh -c '
        for file do
            mv "$file" '"$dest_dir"' && echo "Moved: $file" || echo "Failed to move: $file"
        done
    ' sh {} +

    # Check if find command found any files
    if [ $(find "$src_dir" -maxdepth 1 -name "$file_pattern" | wc -l) -eq 0 ]; then
        echo "No files found matching the pattern '$file_pattern' in $src_dir."
        return 1
    else
        echo "Move operation completed."
    fi
}

# Calling the function with all passed arguments
move_files "$@"

